<?php

class QDB_ActiveRecord_Runtime {
	static  $tpl = "
class model_runtime_[table_name] extends QDB_ActiveRecord_Abstract {
	
	static function __define() {
		return array(
			'behaviors'=>'',
			'behaviors_settings'=>array(
			
			),
			'table_name'=>'[table_name]',
			'props'=>array(
				
			),
			'attr_accessible'=>'',
			'attr_protected'=>'',
			'create_reject'=>'',
			'update_reject'=>'',
			
			'create_autofill'=>array(
			),
			
			'update_autofill'=>array(
			),
			
			'validations'=>array(
			),
		);
	}
	
	static function find()
    {
        $args = func_get_args();
        return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs(\$args);
    }
    
    static function meta()
    {
        return QDB_ActiveRecord_Meta::instance(__CLASS__);
    }
}
";
	static function instance($tablename) {
		
		$class_name = 'model_runtime_'.$tablename ;
		if(class_exists($class_name)) return new $class_name() ;		
		$filename = Q::ini('runtime_cache_dir').'/'.$class_name.'.php' ;
		if(file_exists($filename)) {
			require_once($filename) ;
			if(!class_exists($class_name)) {
				@unlink($filename) ;
				exit("can not find class $class_name") ;
			}
			return new $class_name () ;
		} else {
			self::$out='<?php'.str_replace('[table_name]',$tablename,self::$tpl).' ?>' ;
			file_put_contents($filename,self::$out) or exit("cannot write $filename") ;
			return self::instance($tablename) ;
		}
	}
}
?>